//
//  XGMineViewModel.swift
//  TodayNews
//
//  Created by monkey on 2020/2/3.
//  Copyright © 2020 itcast. All rights reserved.
//

import Foundation
import SwiftyJSON

class XGMineViewModel
{
    /// 设置项数组
    private(set) var items:[[XGMineItemModel]]?
    /// 关注用户
    private(set) var concernUsers: [XGConcernUserModel]?
}

// MARK: - 网络相关

extension XGMineViewModel
{
    /// 获取我的页面设置列表数据
    /// - Parameter completionHandle: 完成回调
    func fetchMineList(completionHandle: @escaping(Bool) -> Void) -> Void
    {
        AlamofireTool.loadMineListData { (responseObject, error) in
            if responseObject == nil || error != nil {
                XGPrint("加载我的页面设置列表数据失败!")
                completionHandle(false)
                return
            }
            
            let jsonObject = JSON(responseObject!)
            guard let sections = jsonObject["data"].dictionary,
                let itemsArray = sections["sections"]?.array else {
                    XGPrint("json解析错误")
                    completionHandle(false)
                    return
            }
            
            self.items = itemsArray.compactMap { (items) -> [XGMineItemModel]? in
                return items.array?.compactMap({ (dict) -> XGMineItemModel? in
                    return XGMineItemModel.deserialize(from: dict.dictionaryObject)
                })
            }
            let concernItem = XGMineItemModel.deserialize(from: ["text": "我的关注"])!
            self.items?.insert([concernItem], at: 0)
            completionHandle(true)
        }
    }
    
    /// 获取我的关注数据
    /// - Parameter completionHandle: 完成回调
    func fetchConcernUsers(completionHandle: @escaping(Bool) -> Void) -> Void
    {
        AlamofireTool.loadMineConcernData { (responseObject, error) in
            if responseObject == nil || error != nil {
                XGPrint("加载我的关注数据失败!")
                completionHandle(false)
                return
            }
            
            let jsonObject = JSON(responseObject!)
            let dataArray = jsonObject["data"].array
            self.concernUsers = dataArray?.compactMap { (dict) -> XGConcernUserModel? in
                return XGConcernUserModel.deserialize(from: dict.dictionaryObject)
            }
            
            //            let users = dataArray.compactMap { (dict) -> XGConcernUserModel? in
            //                return XGConcernUserModel.deserialize(from: dict.dictionaryObject)
            //            }
            
            // 测试1个关注用户
            //             if users.count > 1 {
            //             self.concernUsers = Array(users.prefix(1))
            //             }
            
            completionHandle(true)
        }
    }    
}
